<?php

namespace App\Http\Service;

use Illuminate\Http\Request;
use App\Traits\FileUploadTrait;
use DB;


/**
* 文件上传
*/
class FileService
{
	use FileUploadTrait;
	private static $_obj;

	public static function getObjectData()
	{
		if (!self::$_obj instanceof self) {
			self::$_obj = new self();
		}
		return self::$_obj;
	}

	public function storeFile($file,$filetype='')
	{
		if (!is_null($file)) {
			$options = $this->getUploads($filetype);
			$fileObj = $this->upload($file,$options);
			if (!empty($fileObj) && isset($fileObj->savePath)) {
				$img = $fileObj->savePath;
			}
			$url = $this->showUploadImg($img,$filetype);
		}
		return !empty($url) ? $url : false;	

	}

	//
	public function getUploads($type='article')
	{
		$options = [];
        $options['prefix'] = config("backend.fileupload.prefix.".$type);
        $options['upload_path'] = config("backend.fileupload.path.".$type);
        $options['dir_structure'] = config('backend.fileupload.dir_structure');
        return $options;	
	}

	public function showUploadImg($imgUrl,$type='article')
	{
		$defaultImg = '';
        $baseUrl = '';
        $this->fileImgUrl = config('backend.fileupload.dir.{$type}');
        $baseUrl = $this->fileImgUrl;

        return !empty($imgUrl) ? '/' . $baseUrl . $imgUrl : $defaultImg;
        
	}

	public function delFile($id,$type="article",$imgUrl='')
	{
		if (!$imgUrl){
			$imgUrl = DB::table("videos")->where("id",$id)->select('video')->first()->video;
		}
		$fileImgUrl = rtrim(config('backend.fileupload.dir.'.$type),'/');
		if(@unlink($_SERVER['DOCUMENT_ROOT'].'/'.$fileImgUrl.$imgUrl)){
			return $fileImgUrl;
		}else{
			return $fileImgUrl;
		}
	}

}